package com.yulongtian.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.yulongtian.entity.TemHumData;
import com.yulongtian.mapper.TemHumDataMapper;
import com.yulongtian.service.TemHumDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulongtian.vo.TemHumDataOutFileVO;
import com.yulongtian.vo.TemHumDataVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yulongtian
 * @since 2022-11-15
 */
@Service
public class TemHumDataServiceImpl extends ServiceImpl<TemHumDataMapper, TemHumData> implements TemHumDataService {

    @Override
    public List<TemHumData> getDataByDeviceCode(String deviceCode) {
        return baseMapper.getDataByDeviceCode(deviceCode);
    }

    @Override
    public List<TemHumData> getDataByDeviceCodePage(String deviceCode, String bigTem, String smlTem, String bigHum, String smlHum,
                                                    String bigAdcx, String smlAdcx, String beep, String led, String bigCreateTime, String smlCreateTime) {
        TemHumDataVO temHumData = new TemHumDataVO();

        //指定日期格式
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if (deviceCode != null && !deviceCode.equals("")) {
            temHumData.setDeviceCode(deviceCode);
        }
        if (!bigTem.equals("null") && !bigTem.equals("")) {
            temHumData.setBigTem(bigTem);
        }
        if (!smlTem.equals("null") && !smlTem.equals("")) {
            temHumData.setSmlTem(smlTem);
        }
        if (!bigHum.equals("null") && !bigHum.equals("")) {
            temHumData.setBigHum(bigHum);
        }
        if (!smlHum.equals("null") && !smlHum.equals("")) {
            temHumData.setSmlHum(smlHum);
        }
        if (!bigAdcx.equals("null") && !bigAdcx.equals("")) {
            temHumData.setBigAdcx(bigAdcx);
        }
        if (!smlAdcx.equals("null") && !smlAdcx.equals("")) {
            temHumData.setSmlAdcx(smlAdcx);
        }
        if (!beep.equals("null") && !beep.equals("")) {
            temHumData.setBeepState(Integer.valueOf(beep));
        }
        if (!led.equals("null") && !led.equals("")) {
            temHumData.setLedState(Integer.valueOf(led));
        }
        if (!bigCreateTime.equals("null") && !bigCreateTime.equals("")) {
            temHumData.setBigCreateTime(LocalDateTime.parse(bigCreateTime, format));
        }
        if (!smlCreateTime.equals("null") && !smlCreateTime.equals("")) {
            temHumData.setSmlCreateTime(LocalDateTime.parse(smlCreateTime, format));
        }
        return baseMapper.getDataByDeviceCodePage(temHumData);
    }

    @Override
    public void deleteById(String id) {
//        TemHumData temHumDataById = baseMapper.selectById(Integer.parseInt(id));
//        temHumDataById.setIsDelete(1);
//        baseMapper.updateById(temHumDataById);
        //lambda表达式修改
        this.lambdaUpdate().set(TemHumData::getIsDelete, 1).eq(TemHumData::getId, Integer.parseInt(id)).update();
    }

    @Override
    public void getFileOutExcel(HttpServletResponse response, String deviceCode, String bigTem, String smlTem, String bigHum, String smlHum, String bigAdcx, String smlAdcx, String beep, String led, String bigCreateTime, String smlCreateTime) {
        try {
            TemHumDataVO temHumData = new TemHumDataVO();

            //指定日期格式
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            if (deviceCode != null && !deviceCode.equals("")) {
                temHumData.setDeviceCode(deviceCode);
            }
            if (!bigTem.equals("null") && !bigTem.equals("")) {
                temHumData.setBigTem(bigTem);
            }
            if (!smlTem.equals("null") && !smlTem.equals("")) {
                temHumData.setSmlTem(smlTem);
            }
            if (!bigHum.equals("null") && !bigHum.equals("")) {
                temHumData.setBigHum(bigHum);
            }
            if (!smlHum.equals("null") && !smlHum.equals("")) {
                temHumData.setSmlHum(smlHum);
            }
            if (!bigAdcx.equals("null") && !bigAdcx.equals("")) {
                temHumData.setBigAdcx(bigAdcx);
            }
            if (!smlAdcx.equals("null") && !smlAdcx.equals("")) {
                temHumData.setSmlAdcx(smlAdcx);
            }
            if (!beep.equals("null") && !beep.equals("")) {
                temHumData.setBeepState(Integer.valueOf(beep));
            }
            if (!led.equals("null") && !led.equals("")) {
                temHumData.setLedState(Integer.valueOf(led));
            }
            if (!bigCreateTime.equals("null") && !bigCreateTime.equals("")) {
                temHumData.setBigCreateTime(LocalDateTime.parse(bigCreateTime, format));
            }
            if (!smlCreateTime.equals("null") && !smlCreateTime.equals("")) {
                temHumData.setSmlCreateTime(LocalDateTime.parse(smlCreateTime, format));
            }
            List<TemHumData> deviceCodePage = baseMapper.getDataByDeviceCodePage(temHumData);
            List<TemHumDataOutFileVO> temHumDataOutFileVOList = new ArrayList<>();
            String[] status = {"关闭", "开启"};
            for (TemHumData humData : deviceCodePage) {
                TemHumDataOutFileVO temHumDataOutFileVO = new TemHumDataOutFileVO();
                BeanUtils.copyProperties(humData, temHumDataOutFileVO);
                temHumDataOutFileVO.setBeepState(status[humData.getBeepState()]);
                temHumDataOutFileVO.setLedState(status[humData.getLedState()]);
                temHumDataOutFileVOList.add(temHumDataOutFileVO);
            }
            //时间
            String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            //设置响应字符集
            response.setCharacterEncoding("UTF-8");
            //设置响应媒体类型
            response.setContentType("application/octet-stream");
            //定义输出文件名称
            String sheetName = "数据汇总";
            String fileName = "数据汇总表-" + str;
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TemHumDataOutFileVO.class).autoCloseStream(Boolean.FALSE)
                    .sheet(sheetName)
                    // 设置字段宽度为自动调整
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .doWrite(temHumDataOutFileVOList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public HashMap<String, Object> zheXianTuShowTem(String deviceCode, String bigCreateTime, String smlCreateTime) {
        LocalDateTime parseBigCreateTime = null;
        LocalDateTime parseSmlCreateTime = null;
        //指定日期格式
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (!bigCreateTime.equals("null") && !bigCreateTime.equals("")) {
            parseBigCreateTime = LocalDateTime.parse(bigCreateTime, format);
        }
        if (!smlCreateTime.equals("null") && !smlCreateTime.equals("")) {
            parseSmlCreateTime = LocalDateTime.parse(smlCreateTime, format);
        }
        List<TemHumData> temHumDatas = baseMapper.zheXianTuShowTem(deviceCode, parseBigCreateTime, parseSmlCreateTime);

        double[] temValue = new double[temHumDatas.size()];
        double[] humValue = new double[temHumDatas.size()];
        double[] adcxValue = new double[temHumDatas.size()];
        LocalDateTime[] times = new LocalDateTime[temHumDatas.size()];


        //最低温度
        double minTem = 200;
        //最高温度
        double maxTem = 0;
        //平均温度
        double avgTem = 0;

        //最低湿度
        double minHum = 200;
        //最高湿度
        double maxHum = 0;
        //平均湿度
        double avgHum = 0;

        //最低光照强度
        double minAdcx = 200;
        //最高光照强度
        double maxAdcx = 0;
        //平均光照强度
        double avgAdcx = 0;

        double temSum = 0;
        double humSum = 0;
        double adcxSum = 0;

        //转换格式
        DecimalFormat df = new DecimalFormat("#.00");


        for (int i = 0; i < temHumDatas.size(); i++) {
            TemHumData temHumData = temHumDatas.get(i);

            temValue[i] = Double.valueOf(df.format(Double.parseDouble(temHumData.getTem())));
            humValue[i] = Double.valueOf(df.format(Double.parseDouble(temHumData.getHum())));
            adcxValue[i] = Double.valueOf(df.format(Double.parseDouble(temHumData.getAdcx())));


            times[i] = temHumData.getCreatTime();

            minTem = Math.min(temValue[i], minTem);
            minHum = Math.min(humValue[i], minHum);
            minAdcx = Math.min(adcxValue[i], minAdcx);

            maxTem = Math.max(temValue[i], maxTem);
            maxHum = Math.max(humValue[i], maxHum);
            maxAdcx = Math.max(adcxValue[i], maxAdcx);

            temSum += temValue[i];
            humSum += humValue[i];
            adcxSum += adcxValue[i];

        }

        avgTem = Double.valueOf(df.format(Double.valueOf(temSum / temHumDatas.size())));
        avgHum = Double.valueOf(df.format(Double.valueOf(humSum / temHumDatas.size())));
        avgAdcx = Double.valueOf(df.format(Double.valueOf(adcxSum / temHumDatas.size())));

        HashMap<String, Object> res = new HashMap<>();

        res.put("temValue", temValue);
        res.put("humValue", humValue);
        res.put("adcxValue", adcxValue);
        res.put("times", times);
        res.put("maxTem", maxTem);
        res.put("avgTem", avgTem);
        res.put("minHum", minHum);
        res.put("maxHum", maxHum);
        res.put("minTem", minTem);
        res.put("avgHum", avgHum);
        res.put("minAdcx", minAdcx);
        res.put("maxAdcx", maxAdcx);
        res.put("avgAdcx", avgAdcx);

        return res;


    }
}
